<template>
	<view>
		<v-popup v-model:value="isShow" :title="title" :scrollHeight="scrollHeight" @close="handleClose" @confirm="handleConfirm">
			<view class="popup-content">
				<view v-for="(item, index) in safeList" :key="index" class="picker-item" :class="{ active: item.value === selectedValue }" @click="handleSelect(item)">
					{{ item.label }}
				</view>
				<view v-show="safeList.length === 0">
					<slot name="is-null">
						<v-null text="暂无数据"></v-null>
					</slot>
				</view>
			</view>
		</v-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, watch,inject } from 'vue';

interface PickerItem {
	label: string;
	value: string | number;
}
/**
 * v-picker 拾取器
 * value 是否显示拾取器 默认值:false  可选值true显示、false隐藏
 * list 拾取器数据列表
 * title 拾取器标题
 * selected 默认选中项 默认值:null
 * scrollHeight 拾取器滚动区域高度 默认值:400
 * 相关事件:confirm 选中事件 select选择事件
 */
const props = defineProps({
	value: {
		type: Boolean,
		default: false,
		required: true
	},
	list: {
		type: Array as () => PickerItem[],
		required: true
	},
	title: {
		type: String,
		default: ''
	},
	selected: {
		type: [String, Number],
		default: null
	},
	scrollHeight: {
		type: Number,
		default: 400
	}
});

const emit = defineEmits(['update:value', 'close', 'confirm', 'select']);

const isShow = ref(props.value);
// 安全列表计算属性
const safeList = computed(() => props.list || []);
const selectedValue = ref(
  props.selected !== null && props.selected !== undefined
    ? props.selected
    : (safeList.value.length > 0 && safeList.value[0].value !== undefined ? safeList.value[0].value : '')
);
const config = inject<any>('config');
const selectedItem = computed(() => {
	return safeList.value.find((item) => item.value === selectedValue.value) || null;
});

watch(
	() => props.value,
	(newValue) => {
		isShow.value = newValue;
	}
);

function handleClose() {
	isShow.value = false;
	emit('update:value', false);
	emit('close', false);
}

function handleSelect(item: PickerItem) {
	selectedValue.value = item.value;
	emit('select', item);
}

function handleConfirm() {
	isShow.value = false;
	emit('confirm', selectedItem.value);
	emit('update:value', false);
}
</script>
<style lang="scss">
.picker-item {
	padding: 20rpx 30rpx;
	font-size: v-bind("config.fontSize.mediumText");
	color: v-bind("config.fontColor.mainText");
	border-bottom: 1rpx solid v-bind("config.border.color");
}

.picker-item.active {
	color: v-bind("config.fontColor.default");
	font-weight: 500;
}
</style>
